package com.test.rabbitmq;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author : caili
 * @date : 10:12 2023/1/17
 */
@Component
@Slf4j
public class TopicReceiver {
    @Autowired
    RabbitTemplate rabbitTemplate;

    /**
     * "*"代表一个单词，"#"代表0到多个单词
     * @param pMessage
     * @param message
     * @param channel
     * @throws Exception
     */
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue("topicQueue1"),
                    exchange = @Exchange(value = "topicExchange",type = ExchangeTypes.TOPIC),//自定交换机名称和类型
                    key = "topicRoutKey.test.*" //路由key
            )
    }, ackMode = "MANUAL")
    @RabbitHandler
    public void process(String pMessage, Message message, Channel channel) throws Exception {
        //消费者1接收100条信息
        log.info("[主题模式]消费者1接收生产中消息:{}", pMessage);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //设置手动应答 方便演示不做业务逻辑和异常处理了
        channel.basicAck(deliveryTag, false);
    }

    //"*"代表一个单词，"#"代表0到多个单词
    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue("topicQueue2"),
                    exchange = @Exchange(value = "topicExchange",type = ExchangeTypes.TOPIC),//自定交换机名称和类型
                    key = "topicRoutKey.#" //路由key
            )
    }, ackMode = "MANUAL")
    @RabbitHandler
    public void process2(String pMessage, Message message, Channel channel) throws Exception {
        //消费者2接收100条信息
        log.info("[主题模式]消费者2接收生产中消息:{}", pMessage);
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //设置手动应答 方便演示不做业务逻辑和异常处理了
        channel.basicAck(deliveryTag, false);
    }
}
